/*
 * @lc app=leetcode id=482 lang=cpp
 *
 * [482] License Key Formatting
 */

// @lc code=start
class Solution {
public:
    string licenseKeyFormatting(string s, int k) {
        int cnt = 0;
        for (auto c :s) {
            cnt += (c != '-');
        }
        if (cnt == 0) {
            return {};
        }
        int n = cnt % k;
        n = n == 0 ? k : n;
        int m = cnt / k;
        std::string str;
        str.reserve(cnt + m);     
        bool flag = false;
        int i = 0;
        for (auto c : s) {
            if (c != '-') {
                auto cc = toupper(c);
                str.push_back(cc);
                i++;
                if ((flag && i == k) || (!flag && i == n)) {
                    flag = true;
                    i = 0;
                    str.push_back('-');
                }
            }        
        }
        str.pop_back();
       
        return str;
    }
};
// @lc code=end

